/**
 * @desc 相关操作
 * @author liqiang
 * @company fivefire
 * @date 24 Nov 2017
 */

'use strict'

const api = require('../util/api')
const util = require('../util/util')
const logger = require('../util/logger')
const config = require('../config')

module.exports = {
  login () {
    return wx._login()
      .then(data => api.user.getToken({data: {
        code: data.code,
        wxAppId: config.appid
      }}))
      .then(res => res.data)
      .catch(err => {
        logger.error(err)
        util.showModal(err)
        return {}
      })
  },
  getSmsCode (phoneNo) {
    return api.user.sms({
      loading: false,
      data: {
        type: 2,
        phoneNo
      }
    })
  },
  chooseLocation () {
    return wx._getSetting().then(res => {
      if (res.authSetting['scope.userLocation'] === false) {
        util.showModal({
          title: '地理位置未授权',
          content: '如需正常使用定位功能，请按确定并在授权管理中选中“地理位置”，然后点按确定并返回',
          showCancel: true,
          confirmText: '确认'
        }).then(res => {
          if (res.confirm) {
            // 用户点击确认，前往设置页面
            wx._openSetting()
          }
        })
      } else {
        return wx._chooseLocation()
      }
    })
  },
  checkWxAuthSetting (scope = 'userInfo', title = '', errMsg = '') {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success (res) {
          const setting = res.authSetting
          if (util.isEmptyObject(setting)) {
            // 首次授权
            wx._authorize({ scope: `scope.${scope}` })
              .then(() => {
                // 再次检查一遍setting
                wx.getSetting({
                  success (res) {
                    if (res.authSetting[`scope.${scope}`]) {
                      resolve()
                    } else {
                      showWxUnauthModal(title, errMsg)
                      reject()
                    }
                  },
                  fail: reject
                })
              })
              .catch(err => {
                logger.error(err)
                showWxUnauthModal(title, errMsg)
                reject()
              })
          } else if (setting[`scope.${scope}`] === false) {
            // 曾经拒绝获取权限，显示弹框，确认后前往权限设置页
            showWxUnauthModal(title, errMsg)
            reject()
          } else {
            // 允许获取权限
            resolve()
          }
        },
        fail: reject
      })
    })
  }
}

function showWxUnauthModal (title, errMsg) {
  return util.showModal({
    title: title || '用户未授权',
    content: errMsg || '如需正常使用小程序，请您授权微信昵称和图像'
  }).then(res => {
    if (res.confirm) {
      // 用户点击确认，前往设置页面
      wx._openSetting()
    }
  })
}
